import re 
import numpy as np
import os, sys
import codecs


def get_dict_from_file(scp_path):
    dict_ = {}
    whitespace = re.compile(r'[\t]+')
    with open(scp_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            #utt_id, feat_path, label_path = whitespace.split(line)
            utt_id, feat_path, label_path = line.split()
            dict_[utt_id] = {"feats": feat_path, "labels": label_path}
    return dict_
    
    
def generate_data(scp_path):
    wav_scp = get_dict_from_file(scp_path)
    return wav_scp


def get_dict_from_scp(feats_scp_list, labels_scp_list):
    if not os.path.exists(feats_scp_list) or not os.path.exists(labels_scp_list):
        raise FileNotFoundError
    feats_list, labels_list = [], []
    with codecs.open(filename=feats_scp_list, mode='r') as f:
        feats_list = [line.strip() for line in f.readlines()]
    with codecs.open(filename=labels_scp_list, mode='r') as f:
        labels_list = [line.strip() for line in f.readlines()]

    total_dataset = []
    counter = 0
    for item in zip(feats_list, labels_list):
        if counter < 1:
            print('feats {}\nlabels {}\n'.format(item[0], item[1]))
        total_dataset.append({"feats": item[0], "labels": item[1]})
        counter +=1

    print('{} scps read\n'.format(counter))
    return total_dataset


def from_list_get_data_list(feats_scps, labels_scps):
    return get_dict_from_scp(feats_scps, labels_scps)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print('{} {} {}\n'.format(sys.argv[0], "<feats_scp_list>", "<labels_scp_list>"))
        sys.exit(-1)
    feats_scp_list, labels_scp_list = sys.argv[1], sys.argv[2]
    print('Get feats {}\nlabels{}\n'.format(feats_scp_list, labels_scp_list))
    get_dict_from_scp(feats_scp_list, labels_scp_list)
    print('Done.\n')

      
    
